#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "cJSON.h"
#include <pthread.h>
#include <sys/stat.h>
#include <fcntl.h>

#define N 1024

void *new_sock(void *arg)
{
    printf("will recv new connect\n");
    int sockfd, clientfd;
    char buf[N];
    int addrlen = sizeof(struct sockaddr);
    struct sockaddr_in addr, clientaddr;
    int nbytes;
    // 1创建一个套接字--socket
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        perror("socket err");
        exit(-1);
    }

    // 2定义套接字地址--sockaddr_in
    bzero(&addr, addrlen);
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(6666); //新的连接用6666端口

    // 3绑定套接字--bind
    if (bind(sockfd, (struct sockaddr *)&addr, addrlen) < 0)
    {
        perror("bind err");
        exit(-1);
    }

    // 4启动监听--listen
    if (listen(sockfd, 5) < 0)
    {
        perror("listen err");
        exit(-1);
    }

    // 5接收连接--accept
    clientfd = accept(sockfd, (struct sockaddr *)&clientaddr, &addrlen);
    if (clientfd < 0)
    {
        perror("accept err");
        exit(-1);
    }

    printf("recv new client\n");
    char filename[32] = {0};

    recv(clientfd, buf, N, 0);

    //接收文件名
    printf("recv %s-%d data = %s\n", inet_ntoa(clientaddr.sin_addr),
           ntohs(clientaddr.sin_port), buf);
    cJSON *root = cJSON_Parse(buf);
    cJSON *data = cJSON_GetObjectItem(root, "data");
    cJSON *item = cJSON_GetObjectItem(data, "file_name");
    strcpy(filename, item->valuestring);
    item = cJSON_GetObjectItem(data, "file_len");
    int len1 = item->valueint;
    //回复start
    root = cJSON_CreateObject();
    cJSON_AddItemToObject(root, "type", cJSON_CreateNumber(2));
    data = cJSON_CreateObject();
    cJSON_AddItemToObject(root, "data", data);
    cJSON_AddItemToObject(data, "flag", cJSON_CreateString("start"));
    char *p = cJSON_Print(root);
    send(clientfd, p, strlen(p), 0);
    //接收文件

    int fd = open("/mnt/config/pointtable.json", O_RDWR | O_CREAT, 0777);
    if (fd < 0)
    {
        perror("open err");
    }
   
    while (1)
    {
        bzero(buf, N);
        int len = recv(clientfd, buf, N, 0);
        if (len < 0)
        {
            perror("recv err");
            break;
        }
        else if (len == 0)
        {
            printf("file send complete\n");
            break;
        }
        else
        {
            write(fd, buf, len);
        }
    }

    //回复stop
    root = cJSON_CreateObject();
    cJSON_AddItemToObject(root, "type", cJSON_CreateNumber(2));
    data = cJSON_CreateObject();
    cJSON_AddItemToObject(root, "data", data);
    cJSON_AddItemToObject(data, "flag", cJSON_CreateString("stop"));
    p = cJSON_Print(root);
    send(clientfd, p, strlen(p), 0);
}

int main(int argc, char const *argv[])
{
    //接收局域网的广播包
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        perror("socket err");
        return -1;
    }

    struct sockaddr_in dev_addr;
    dev_addr.sin_family = AF_INET;
    dev_addr.sin_addr.s_addr = INADDR_ANY;
    dev_addr.sin_port = htons(7777);

    socklen_t addrlen = sizeof(dev_addr);
    if (bind(sockfd, (struct sockaddr *)&dev_addr, addrlen) < 0)
    {
        perror("bind err");
        return -1;
    }

    ssize_t len = -1;
    char buf[N] = {0};
    struct sockaddr_in soft_addr;
    memset(buf, 0, N);

    //收到了APP的搜索包
    len = recvfrom(sockfd, buf, N, 0, (struct sockaddr *)&soft_addr, &addrlen);

    //校验一下是否是自家的APP
    if (strcmp(buf, "coffee") == 0)
    {
        printf("收到了自己APP的搜索协议");
    }
    else
    {
        printf("其它的广播，不处理");
        return -1;
    }

    //跑到这里，代表收到自家的搜索了，需要回复
    sendto(sockfd, "yes", strlen(buf), 0, (struct sockaddr *)&soft_addr, addrlen);

    printf("回复了APP\n");

    //化身为服务器，等待APP做长连接
    int serverfd = socket(AF_INET, SOCK_STREAM, 0);
    if (serverfd < 0)
    {
        perror("socket err");
        return -1;
    }

    //绑定自己的地址，可以复用上面UDP的端口，也可以再换一个
    int ret = bind(serverfd, (struct sockaddr *)&dev_addr, addrlen);
    if (ret < 0)
    {
        perror("bind err");
        return -1;
    }

    //启动监听
    ret = listen(serverfd, 5);
    if (ret < 0)
    {
        perror("bind err");
        return -1;
    }

    struct sockaddr_in cliaddr;
    int clifds[2] = {0};
    int clifd = accept(serverfd, (struct sockaddr *)&cliaddr, &addrlen);
    if (clifd < 0)
    {
        perror("accept err");
        return -1;
    }

    printf("APP已经连入\n");

    char buf1[128] = {0};

    recv(clifd, buf1, 128, 0);
    cJSON *root = cJSON_Parse(buf1);
    cJSON *item = cJSON_GetObjectItem(root, "type");
    int type = item->valueint;
    //判断点表存在吗
    FILE *file;
    char *filename = "/mnt/config/pointtable.json";
    file = fopen(filename, "r");
    char *p;
    if (file == NULL) //不存在
    {
        root = cJSON_CreateObject();
        cJSON_AddItemToObject(root, "type", cJSON_CreateNumber(1));
        cJSON_AddItemToObject(root, "result", cJSON_CreateNumber(0));
        cJSON_AddItemToObject(root, "up_config", cJSON_CreateString("ture"));
        p = cJSON_Print(root);
        send(clifd, p, strlen(p), 0);
    }
    else //存在
    {
        fclose(file);
        root = cJSON_CreateObject();
        cJSON_AddItemToObject(root, "type", cJSON_CreateNumber(1));
        cJSON_AddItemToObject(root, "result", cJSON_CreateNumber(0));
        cJSON_AddItemToObject(root, "up_config", cJSON_CreateString("false"));
        p = cJSON_Print(root);
        send(clifd, p, strlen(p), 0);
        printf("sdfdsfsf\n");
        goto loop;
    }
    memset(buf1, 0, sizeof(buf1));

    recv(clifd, buf1, 128, 0);
    if (strcmp(buf1, "new") == 0)
    {
        pthread_t tid;
        if (pthread_create(&tid, NULL, new_sock, NULL) != 0)
        {
            printf("error\n");
        }
    }
    loop:
    while (1)
    {
        memset(buf1, 0, sizeof(buf1));
        recv(clifd, buf1, 128, 0);
        //心跳
        cJSON *root = cJSON_Parse(buf1);
        cJSON *item = cJSON_GetObjectItem(root, "type");
        if (item->valueint == 3)
        {
            root = cJSON_CreateObject();
            cJSON_AddItemToObject(root, "type", cJSON_CreateNumber(3));
            cJSON_AddItemToObject(root, "result", cJSON_CreateNumber(0));
            p = cJSON_Print(root);
            send(clifd, p, strlen(p), 0);
        }
    }
    close(sockfd);

    return 0;
}